# clean environment
rm(list=ls())

# load packages
library(ggplot2)

# load data set with parliamentary inquiries
dat <- read.csv("inquiries.csv")

# create filler variable to sum over
dat$one <- 1

# create decade indicator
dat$decade <- NA
dat$decade[dat$year<1970]<-"1960s"
dat$decade[dat$year>=1970 & dat$year<1980]<-"1970s"
dat$decade[dat$year>=1980 & dat$year<1990]<-"1980s"
dat$decade[dat$year>=1990 & dat$year<2000]<-"1990s"
dat$decade[dat$year>=2000 & dat$year<2010]<-"2000s"
dat$decade[dat$year>=2010 & dat$year<2020]<-"2010s"
dat$decade <- factor(dat$decade, levels=c("1960s", "1970s", "1980s", "1990s", "2000s", "2010s"))

# aggregate number of inquiries by extremism category, party, and decade
shares_df <- aggregate(one ~ extremism_v + party + decade, data=dat, FUN=sum)

# get sum of inquiries by party and decade and merge it to the number of inquries by extremism type
sum_df <- aggregate(one ~ party + decade, data=shares_df, FUN=sum)
shares_df <- merge(shares_df, sum_df, by=c("party", "decade"))

# calculate shares of inquiriess by category, party, and decade
shares_df$share <- shares_df$one.x / shares_df$one.y

# turn to category factor with factor levels 
shares_df$extremism_v <- factor(shares_df$extremism_v, levels=c("right", "left", "both", "unclear", "neither"))

# remove unclear category for plotting purposes
shares_df <- shares_df[shares_df$extremism_v!="unclear",]

# english names of parties
shares_df$party_eng <- NA
shares_df$party_eng[shares_df$party=="AFD"] <- "AfD"
shares_df$party_eng[shares_df$party=="CDU"] <- "CDU/CSU"
shares_df$party_eng[shares_df$party=="FDP"] <- "FDP"
shares_df$party_eng[shares_df$party=="GRUENE"] <- "Greens"
shares_df$party_eng[shares_df$party=="LINKE"] <- "Left Party"
shares_df$party_eng[shares_df$party=="SPD"] <- "SPD"

# bargraph by category and party (AfD excluded bc few years; 1960s excluded bc of low N)
ggplot(data=shares_df[shares_df$party!="AFD" & 
                        shares_df$decade!="1960s",], aes(x=decade, y=share*100, group=extremism_v, color=extremism_v, shape=extremism_v)) + 
  geom_point(stat="identity", size=1.5) +
  geom_line() +
  ylab("Percent") + xlab("Decade") +
  facet_wrap(~party_eng, nrow=1) + 
  scale_color_manual(values=c("dodgerblue", "firebrick", "purple"), name="Type of Extremism", labels=c("RWE", "LWE", "Both")) +
  scale_shape_manual(values=c(17:15), name="Type of Extremism", labels=c("RWE", "LWE", "Both")) +
  theme_bw() +
  theme(axis.text.x = element_text(angle = 45, hjust=1), text=element_text(size=14),
        panel.grid = element_blank(),
        legend.position = "bottom")

ggsave("Fig3_5.pdf", width=7, height=5)

